package com.hzdesk.media.koreabatchmatvector.logic.persenter;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.hzdesk.media.koreabatchmatvector.R;
import com.hzdesk.media.koreabatchmatvector.adapter.CloudListAdapter;
import com.hzdesk.media.koreabatchmatvector.adapter.WiFiSettingAdapter;
import com.hzdesk.media.koreabatchmatvector.bean.MyWifiInfo;
import com.hzdesk.media.koreabatchmatvector.bean.WifiBean;
import com.hzdesk.media.koreabatchmatvector.config.AppContants;
import com.hzdesk.media.koreabatchmatvector.custom.WifiSupport;
import com.hzdesk.media.koreabatchmatvector.dialog.CancelSaveDialog;
import com.hzdesk.media.koreabatchmatvector.dialog.WifiLinkDialog;
import com.hzdesk.media.koreabatchmatvector.inter.ICancelSaveDialogInter;
import com.hzdesk.media.koreabatchmatvector.inter.IWifiLinkDialogInter;
import com.hzdesk.media.koreabatchmatvector.inter.OnclikedWiFiSetting;
import com.hzdesk.media.koreabatchmatvector.logic.contract.IWiFiSettingContract;
import com.hzdesk.media.koreabatchmatvector.logic.view.MainActivity;
import com.hzdesk.media.koreabatchmatvector.request.WifiManage;
import com.hzdesk.media.koreabatchmatvector.utils.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

/**
 * Created by Administrator on 2018/7/30.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class WiFiSettingPersenter implements IWiFiSettingContract.IWiFiSettingPersenter {
    private String TAG = WiFiSettingPersenter.class.getSimpleName();
    private IWiFiSettingContract.IWiFiSettingView mIWiFiSettingView;
    private WiFiSettingAdapter mWiFiSettingAdapter;
    private WifiManager mWifiManager;
    private List<ScanResult> mScanResults;
    private List<WifiBean> realWifiList = new ArrayList<>();
    private int connectType = 0;//1：连接成功？ 2 正在连接（如果wifi热点列表发生变需要该字段）

    public WiFiSettingPersenter(IWiFiSettingContract.IWiFiSettingView mIWiFiSettingView) {
        this.mIWiFiSettingView = mIWiFiSettingView;
    }
    // todo 初始化
    @Override
    public void initRecyclerView(RecyclerView activityWifiSettingRecyclerview, final Context mContext) {
        LinearLayoutManager    layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        activityWifiSettingRecyclerview.setLayoutManager(layoutManager);
        mWiFiSettingAdapter = new WiFiSettingAdapter(mContext);
        activityWifiSettingRecyclerview.setAdapter(mWiFiSettingAdapter);
        mWiFiSettingAdapter.setmOnclikedWiFiSetting(new OnclikedWiFiSetting() {
            @Override
            public void onClickedItem(int postion) {
                wifiConnect(postion, mContext);
            }
        });
    }
    // 点击连接wifi
    private void wifiConnect(int postion, Context mContext) {
        WifiBean mWifiBean =   realWifiList.get(postion);
        if(mWifiBean != null ){
            if(WifiSupport.getWifiCipher(mWifiBean.getCapabilities())==WifiSupport.WifiCipherType.WIFICIPHER_NOPASS){ //无需密码
                WifiConfiguration tempConfig  = WifiSupport.isExsits(mWifiBean.getWifiName(),mContext);
                if(tempConfig == null){
                    WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mWifiBean.getWifiName(),null,WifiSupport.WifiCipherType.WIFICIPHER_NOPASS);
                    WifiSupport.addNetWork(wifiConfiguration,mContext);
                }else{
                    WifiSupport.addNetWork(tempConfig,mContext);
                }
            }else{   //需要密码，弹出输入密码dialog
                // 判断是否连接过
               boolean flag =  isSavaWifiPasswd(mWifiBean);
               if(!flag){
                   noConfigurationWifi(mWifiBean,mContext);
               }else{
                   //todo wifi 是连接过并且保存过密码  弹框 取消连接
                   CancelSaveDialog(mWifiBean,mContext);

               }
            }
        }
    }


    /**
     * @ 判断wifi 是否连接过并且保存过密码
     * */
    private boolean isSavaWifiPasswd(WifiBean mWifiBean) {
        boolean flag = false;
        try {
            WifiManage wifiManage = new WifiManage();
            List<MyWifiInfo> wifiInfos = wifiManage.Read();
            if(wifiInfos!= null && wifiInfos.size() >0){
                for (MyWifiInfo wifiInfo : wifiInfos) {
                    if(mWifiBean.getWifiName().equals(wifiInfo.getSsid())&& !wifiInfo.getPassword().equals("无密码")){
                         // todo 有保存
                        flag = true;
                    }
                }
            }
        } catch (Exception e) {}
        return  flag;
    }

    //之前没配置过该网络， 弹出输入密码界面
    private void noConfigurationWifi(WifiBean mWifiBean, final Context mContext) {
        final WifiLinkDialog linkDialog = new WifiLinkDialog(mContext, R.style.dialog_download,mWifiBean);
        if(!linkDialog.isShowing()){
            linkDialog.show();
        }
        linkDialog.setmIWifiLinkDialogInter(new IWifiLinkDialogInter() {
            @Override
            public void OnClickedDetermine(WifiBean mWifiBean, String inputPassword) {
                WifiConfiguration tempConfig = WifiSupport.isExsits(mWifiBean.getWifiName(),mContext);
                if (tempConfig == null) {
                    WifiConfiguration wifiConfiguration = WifiSupport.createWifiConfig(mWifiBean.getWifiName(),inputPassword, WifiSupport.getWifiCipher(mWifiBean.getCapabilities()));
                    WifiSupport.addNetWork(wifiConfiguration,mContext);
                } else {
                    WifiSupport.addNetWork(tempConfig, mContext);
                }

                linkDialog.dismiss();
            }
            @Override
            public void OnClickedCancel() {
                linkDialog.dismiss();
            }
        });
    }
    /**
     * @desc 取消保存
     * */
    private void CancelSaveDialog(WifiBean mWifiBean, Context mContext) {
        final CancelSaveDialog cancelSaveDialog = new CancelSaveDialog(mContext,R.style.dialog_download,mWifiBean);
        if(!cancelSaveDialog.isShowing()){
            cancelSaveDialog.show();
        }
        cancelSaveDialog.setmICancelSaveDialogInter(new ICancelSaveDialogInter() {
            @Override
            public void OnClickedDetermine(WifiBean mWifiBean) {
                //  取消保存
                removeWifiBySsid(mWifiManager,"\"" + mWifiBean.getWifiName() + "\"");
                cancelSaveDialog.dismiss();
            }

            @Override
            public void OnClickedCancel() {
                cancelSaveDialog.dismiss();
            }
        });
    }
    /**
     * 忘记某一个wifi密码
     *
     * @param wifiManager
     * @param targetSsid
     */
    public  void removeWifiBySsid(WifiManager wifiManager, String targetSsid) {
        List<WifiConfiguration> wifiConfigs = wifiManager.getConfiguredNetworks();
        if(wifiConfigs != null && wifiConfigs.size() > 0){
            for (WifiConfiguration wifiConfig : wifiConfigs) {
                String ssid = wifiConfig.SSID;
                if (ssid.equals(targetSsid)) {
                    wifiManager.removeNetwork(wifiConfig.networkId);
                    wifiManager.saveConfiguration();

                }
            }
        }

    }
    @Override
    public void initWifi(Context mContext) {
        mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()){  //已经打开了wifi
            mIWiFiSettingView.showProgress();
            mIWiFiSettingView.showOpen();
            //requestPermission(mContext);
        }else{//没有打开了wifi
            mIWiFiSettingView.hidenProgress();
            mIWiFiSettingView.showcloase();
            // 清空容器wifi 信息
            clearAll();

        }
    }
    // todo 注册 数据接收广播 ========================================================
    @Override
    public void registeredWifiDate( Context mContext) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        mContext.registerReceiver(mMyReceiver, filter);
    }

    @Override
    public void unRegisteredWifiDate( Context mContext) {
        mContext.unregisterReceiver(mMyReceiver);
    }
    /**
     * 广播接收，监听网络
     */
    private BroadcastReceiver mMyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            // wifi已成功扫描到可用wifi。 // 判断wifi是否打开
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                receiveWiFiData();
            }
        }
    };

    // todo 注册 wifi连接监听广播 ========================================================
    @Override
    public void registeredWifiConnect(Context mContext) {
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(WifiManager.RSSI_CHANGED_ACTION); //信号强度变化
        mFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        mFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        mFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        mFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);//监听wifi列表变化（开启一个热点或者关闭一个热点）
        mContext.registerReceiver(mReceiver, mFilter);
    }

    @Override
    public void unRegisteredWifiConnect(Context mContext) {
        mContext.unregisterReceiver(mReceiver);

    }
    private BroadcastReceiver mReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
          //  Log.e(TAG, "onReceive:action===================2222222222222222222222   "+action);
            switch (action) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (info.getDetailedState().equals(NetworkInfo.DetailedState.DISCONNECTED)) {
                        //wifi已断开
                        Log.e(TAG, "onReceive:wifi没连接上   ");
                        if(realWifiList.size()>0 && mWiFiSettingAdapter != null){
                            for (int i = 0; i < realWifiList.size(); i++) {
                                realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
                            }
                            mWiFiSettingAdapter.notifyDataSetChanged();
                        }
                    } else if (info.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTING)) {
                        //正在连接...
                        Log.e(TAG, "onReceive:wifi正在连接   ");
                        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(context);
                        connectType = 2;
                        wifiListSet(connectedWifiInfo.getSSID(),connectType);
                    } else if (info.getDetailedState().equals(NetworkInfo.DetailedState.CONNECTED)) {
                        //连接到网络
                        Log.e(TAG, "onReceive:wifi连接上了   ");
                        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(context);
                        connectType = 1;
                        wifiListSet(connectedWifiInfo.getSSID(),connectType);
                    }else if(info.getDetailedState().equals(NetworkInfo.DetailedState.OBTAINING_IPADDR)){
                        //正在获取IP地址
                        Log.e(TAG, "onReceive:正在获取IP地址   ");
                        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(context);
                        connectType = 3;
                        wifiListSet(connectedWifiInfo.getSSID(),connectType);;
                    }else if(info.getDetailedState().equals(NetworkInfo.DetailedState.FAILED)){
                        //连接失败
                        Log.e(TAG, "onReceive:连接失败   ");
                    }
                    break;
                case WifiManager.WIFI_STATE_CHANGED_ACTION:
                    int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                    switch (wifiState) {
                        case WifiManager.WIFI_STATE_ENABLING://wifi正在启用
                            break;
                        case WifiManager.WIFI_STATE_ENABLED://Wifi已启用
                            requestPermission(context);
                            break;
                    }
                    break;
                case WifiManager.SUPPLICANT_STATE_CHANGED_ACTION:
                    int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR, -100);
                    if (error==WifiManager.ERROR_AUTHENTICATING){
                        //wifi密码认证错误！
                        Toast.makeText(context,"密码认证错误",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case WifiManager.NETWORK_IDS_CHANGED_ACTION:
                    //已经配置的网络的ID可能发生变化时
                    Log.e(TAG, "onReceive:已经配置的网络的ID可能发生变化时   ");
                    break;
                case ConnectivityManager.CONNECTIVITY_ACTION:
                    //连接状态发生变化，暂时没用到
                    int type = intent.getIntExtra(ConnectivityManager.EXTRA_NETWORK_TYPE,0);
                    break;
                    case WifiManager.SCAN_RESULTS_AVAILABLE_ACTION:
                        wifiListChange(context);
                        break;

            }
        }
    };
    /**
     * //网络状态发生改变 调用此方法！
     * @param context
     */
    public void wifiListChange(Context context){
        sortScaResult();
        WifiInfo connectedWifiInfo = WifiSupport.getConnectedWifiInfo(context);
        if(connectedWifiInfo != null){
            wifiListSet(connectedWifiInfo.getSSID(),connectType);
        }
    }
    /**
     * 将"已连接"或者"正在连接"的wifi热点放置在第一个位置
     * @param wifiName
     * @param type
     */
    public void wifiListSet(String wifiName , int type){
        int index = -1;
        WifiBean wifiInfo = new WifiBean();
        if(CollectionUtils.isNullOrEmpty(realWifiList)){
            return;
        }
        for(int i = 0;i < realWifiList.size();i++){
            realWifiList.get(i).setState(AppContants.WIFI_STATE_UNCONNECT);
        }
        Collections.sort(realWifiList);//根据信号强度排序
        for(int i = 0;i < realWifiList.size();i++){
            WifiBean wifiBean = realWifiList.get(i);
            if(index == -1 && ("\"" + wifiBean.getWifiName() + "\"").equals(wifiName)){
                index = i;
                wifiInfo.setLevel(wifiBean.getLevel());
                wifiInfo.setWifiName(wifiBean.getWifiName());
                wifiInfo.setCapabilities(wifiBean.getCapabilities());
                if(type == 1){
                    wifiInfo.setState(AppContants.WIFI_STATE_CONNECT);
                }else if(type == 2){
                    wifiInfo.setState(AppContants.WIFI_STATE_ON_CONNECTING);
                }else if(type == 3){
                    wifiInfo.setState(AppContants.WIFI_STATE_ISGETIP);
                }
            }
        }
        if(index != -1){
            realWifiList.remove(index);
            realWifiList.add(0, wifiInfo);
            mWiFiSettingAdapter.notifyDataSetChanged();
        }
    }
    // todo 点击返回
    @Override
    public void onclikcedWiFiSettingbacak() {
        mIWiFiSettingView.WiFiSettingbacak();
    }
    // todo 点击打开关闭
    @Override
    public void onClickedWiFiOpenOrCloes( Context mContext) {
        if (mWifiManager.isWifiEnabled()) {  //todo 关闭wifi
            mIWiFiSettingView.hidenProgress();
            mWifiManager.setWifiEnabled(false);
            mIWiFiSettingView.showcloase();
           // 清空容器wifi 信息
            clearAll();
        }else{  //todo 打开wifi
            mIWiFiSettingView.showProgress();
            mWifiManager.setWifiEnabled(true);
            mIWiFiSettingView.showOpen();
            // todo 申请权限
           //requestPermission(mContext);
        }
    }
    private void requestPermission(Context mContext) {
        List<PermissionItem> permissonItems = new ArrayList<PermissionItem>();
        permissonItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, "wifi", R.drawable.ic_launcher_background));
        permissonItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, "定位", R.drawable.permission_ic_location));
        HiPermission.create(mContext).permissions(permissonItems).checkMutiPermission(new PermissionCallback() {
            @Override
            public void onClose() {
                Log.e(TAG, "onClose: " );
            }

            @Override
            public void onFinish() {
                Log.e(TAG, "onFinish: " );
                startScan();
            }

            @Override
            public void onDeny(String permission, int position) {
                Log.e(TAG, "onDeny: " );
            }

            @Override
            public void onGuarantee(String permission, int position) {
                Log.e(TAG, "onGuarantee: " );
               // startScan();
            }
        });
    }
    // 打开wifi 搜索
    @Override
    public void startScan() {
        mWifiManager.startScan();
    }
    // 广播监听到wifi 信息
    @Override
    public void receiveWiFiData() {
        if(mScanResults != null && realWifiList != null){
            mScanResults.clear();
            realWifiList.clear();
        }
        mScanResults =  WifiSupport.noSameName(mWifiManager.getScanResults());
        if(mScanResults != null){
            //todo  数据转换
            sortScaResult();
        }
    }


    /**
     * 获取wifi列表然后将bean转成自己定义的WifiBean 放到适配器中
     */
    private void sortScaResult(){
        if(mScanResults != null){
            for(int i = 0;i < mScanResults.size();i++){
                WifiBean wifiBean = new WifiBean();
                wifiBean.setWifiName(mScanResults.get(i).SSID);
                wifiBean.setState(AppContants.WIFI_STATE_UNCONNECT);   //只要获取都假设设置成未连接，真正的状态都通过广播来确定
                wifiBean.setCapabilities(mScanResults.get(i).capabilities);
                wifiBean.setLevel(WifiSupport.getLevel(mScanResults.get(i).level)+"");
                realWifiList.add(wifiBean);
            }
            //排序
            Collections.sort(realWifiList);
            // todo 隐藏wifi 进度
            mWiFiSettingAdapter.AddItem(realWifiList);
            mIWiFiSettingView.hidenProgress();
        }
    }
    // 清空数据
    private void clearAll(){
        if(mScanResults != null && realWifiList != null && mWiFiSettingAdapter != null){
            realWifiList.clear();
            mScanResults.clear();
            mWiFiSettingAdapter.notifyDataSetChanged();
        }
    }


}
